package com.gitee.hermer.engine.jars.core.zipkin.section;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.gitee.hermer.boot.jee.commons.collection.StringCache;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.core.context.domain.EngineAppInfoContext;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;
import com.gitee.hermer.engine.jars.core.execute.EngineExecuteThread;
import com.gitee.hermer.engine.jars.core.execute.IEngineExecuteSection;

import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.TraceContext;

@Component()
@Scope(EngineConstant.SPRING_SCOPE_PROTOTYPE)
public class ZipkinEngineExecuteSection extends UtilsContext implements IEngineExecuteSection{


	private Tracing tracing;

	private TraceContext traceContext;
	private Tracer tracer;
	private Span span;

	@Override
	public void afterPropertiesSet() throws Exception {

	}

	@Override
	public void destroy() throws Exception {

	}

	@Override
	public void begin(EngineAppInfoContext appContext) {
		try{
			tracing = appContext.getBean(Tracing.class);
			traceContext = tracing.currentTraceContext().get();
			tracer = Tracing.currentTracer();
		}catch (Exception e) {
			error(e.getMessage(),e);
		}
	}
	
	Span createTrace(){
		if(traceContext == null){
			return tracer.newTrace();
		}else{
			return tracer.newChild(traceContext);
		}
	}
	
	@Override
	public void beginExecuteThread(EngineExecuteThread executeThread) {
		if(tracer != null){
			span = createTrace().name(
					new StringCache("job ").append(executeThread.getParamsInfo().getProjectName())
					.append(EngineConstant.STR_SPLIT).append(executeThread.getParamsInfo().getVersion())
					.append(EngineConstant.STR_FILE_SPLIT).append(executeThread.getParamsInfo().getWorkMethod())
					.append(EngineConstant.STR_SPLIT).append(executeThread.getParamsInfo().getWorkVersion()).append("()").toString());
			span.start();
		}
	}

	@Override
	public void endExecuteThread(EngineExecuteThread executeThread) {
		if(span != null){
			span.finish();
		}
	}

	@Override
	public void end(EngineAppInfoContext appContext) {

	}


}
